<?php
namespace app\index\controller\clinic;
use app\index\controller\BaseIndex;
use app\common\model\ClinicAdmin;
use app\common\model\Clinic;
use app\common\model\ClinicAuthGroup;
use think\facade\Session;
use think\facade\Url;
use szktor\Random;
use szktor\ClinicDict; //诊所门店公共字典
use app\common\model\ClinicDictsheet; //字典表数据

/*
* 前台-门店人员设置
*/
class Admin extends BaseIndex
{
    protected $noNeedLogin = [];  //无需登录的方法，同时也就不需要鉴权了
    protected $noNeedRight = ['info','del','dialog_add','edit_myself','edit_password','edit_mobile','build_user_name'];  //无需鉴权的方法，但需要登录

    //初始化
    public function initialize()
    {
        parent::initialize();
    }
    
    //首页
    public function index()
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            $data = $this->request->only(['group_id','keyword','status','page'],'post');
            //条件
            $map = [['a.clinic_id','=', $this->admin['clinic_id']],['a.is_del','=','0']];
            if(isset($data['keyword']) && $data['keyword'] != '')
            {
                $map[] = ['a.user_name|a.user_mobile|a.nickname','like','%' . $data['keyword'] . '%'];
            }
            if(strtoupper($data['group_id']) != 'ALL')
            {
                $map[] = ['a.group_id','=',$data['group_id']];
            }
            if(strtoupper($data['status']) != 'ALL')
            {
                $map[] = ['a.status','=',(int)$data['status']];
            }
            $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
            $list = ClinicAdmin::alias('a')->join('clinic_auth_group b', 'a.group_id = b.id', 'left')
                    ->where($map)->field('a.*,b.name as group_name')
                    ->order('a.id desc')->paginate($limit,false,['page' => $data['page'], 'var_page' => 'page']);
            if (count($list) <= 0) {
                return json(['code' => '1', 'msg' => '当前页下的数据已显示完毕！', 'count' => '0', 'data' => []]);
            }
            $res =['code' => 0, 'msg' => '数据加载成功', 'count' => $list->total(), 'data' => $list->items()];
            foreach ($res['data'] as $key => &$val) {
                $val['last_login_time'] = (int)$val['last_login_time'] > 0 ? date('Y-m-d H:i',$val['last_login_time']) : '从未登录';
                $val['sex_txt'] = _getSexTxt((int)$val['sex']);
                if((int)$val['is_supper_admin'] > 0) //超级管理员
                {
                    $val['nickname'] = empty($val['nickname']) ? '超级管理' : $val['nickname'] . '【超管】';
                }
                $val['zhiwei_code_txt'] = _getDictNameTxt($val['zhiwei_code'],ClinicDict::getAdminZhiWeiList());
                $val['group_id_txt'] = '';
            }
            return json($res);
        }
        $this->assign([
            'captcha_key' => md5($this->site['client_uuid'] . '_4'),
            'group_list' => ClinicAuthGroup::getGroupList($this->admin['clinic_id'],true),
            'zhiwei_list' => ClinicDict::getAdminZhiWeiList(), //员工职位列表
            'zhicheng_list' => ClinicDict::getAdminZhiChengList(), //员工医师职称列表
            'zhengjian_list' => ClinicDict::getRenYuanZhengJianList(), //人员证件类型列表
            'xueli_list' => ClinicDict::getRenYuanXueLiList(), //人员学历类型列表
            'keshi_list' => ClinicDictsheet::getClinicKeShiList($this->admin['clinic_id'],true,'id,pid,name',['status' => '1']), //获取科室列表 Select 选择器使用
        ]);
        return $this->view->fetch();
    }
    //添加+修改
    public function info($id = 0)
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            $data = $this->request->only([
                'nickname','gonghao_code','user_name','user_pwd','group_id','user_mobile','status','sex',
                'keshi_code','zhiwei_code','cert_code','cert_no','biye_xuexiao','xueli_code','zhicheng_code',
                'yishi_cert_no','yishi_cert_img','yishi_cert_senddate','yishi_cert_status',
                'kangjun_cert_no','kangjun_cert_img','kangjun_cert_senddate','kangjun_cert_status','email',
                'img','id','old_user_name','old_mobile',
            ],'post');
            //switch样式选择器值判断
            $data['status'] = isset($data['status']) ? $data['status'] == 'on' ? '1' : '0' : '0';
            $data['yishi_cert_status'] = isset($data['yishi_cert_status']) ? $data['yishi_cert_status'] == 'on' ? '1' : '0' : '0';
            $data['kangjun_cert_status'] = isset($data['kangjun_cert_status']) ? $data['kangjun_cert_status'] == 'on' ? '1' : '0' : '0';
            try
            {
                $info = ClinicAdmin::where(['id' => intval($data['id']), 'clinic_id' => $this->admin['clinic_id'],'is_del' => '0'])->find();
                if(!$info) //信息无效
                {
                    if(!isset($data['user_pwd']) || empty($data['user_pwd']))
                    {
                        return json(['err' => '2', 'msg' => '登录密码不可为空']);
                    }
                }
                //如果要修改密码
                if($data['user_pwd'])
                {
                    $pwdSalt = Random::numeric(5);
                    $userPwd = ClinicAdmin::encryptPassword($data['user_pwd'],$pwdSalt);
                    $data['user_pwd'] = $pwdSalt; //密码
                    $data['pwd_salt'] = $pwdSalt; //密码域
                }else{
                    unset($data['user_pwd']);
                }
                if($info) //信息已存在
                {
                    if($data['user_name'] != $info['user_name'])
                    {
                        $isExists = ClinicAdmin::checkUniqueCode(new ClinicAdmin(),$data['user_name'],'user_name');
                        if($isExists)
                        {
                            return json(['err' => '1', 'msg' => '登录账号' . $data['user_name'] . '已被他人使用']);
                        }
                    }
                    if(strlen($data['user_name']) <= 8)
                    {
                        return json(['err' => '2', 'msg' => '登录账号不可小于8位']);
                    }
                    if($data['old_mobile'] != $info['user_mobile'])
                    {
                        $isExists = ClinicAdmin::checkUniqueCode(new ClinicAdmin(),$data['old_mobile'],'user_mobile');
                        if($isExists)
                        {
                            return json(['err' => '3', 'msg' => '手机' . $data['user_name'] . '已被他人使用']);
                        }
                    }
                    unset($data['id'],$data['old_user_name'],$data['old_mobile']);
                    if((int)$info['is_supper_admin'] > 0) //超级管理员
                    {
                        unset($data['user_name'],$data['user_mobile'],$data['status'],$data['group_id']);
                    }
                    $editRes = ClinicAdmin::where(['id' => $info['id']])->update($data);
                }else{ //信息不存在
                    if(!$data['user_name'])
                    {
                        $data['user_name'] = ClinicAdmin::buildUniqueFieldsVal(5,'user_name'); //生成10位 数字+字母 登录账号
                    }else{
                        $isExists = ClinicAdmin::checkUniqueCode(new ClinicAdmin(),$data['user_name'],'user_name');
                        if($isExists)
                        {
                            return json(['err' => '1', 'msg' => '登录账号' . $data['user_name'] . '已被他人使用']);
                        }
                    }
                    if(strlen($data['user_name']) <= 8)
                    {
                        return json(['err' => '2', 'msg' => '登录账号不可小于8位']);
                    }
                    $isExists = ClinicAdmin::checkUniqueCode(new ClinicAdmin(),$data['user_mobile'],'user_mobile');
                    if($isExists)
                    {
                        return json(['err' => '3', 'msg' => '手机' . $data['user_mobile'] . '已被他人使用']);
                    }
                    $data['clinic_id'] = $this->admin['clinic_id']; //诊所门店表的id
                    $data['create_time'] = time(); //创建时间
                    $editRes = ClinicAdmin::insertGetId($data);
                }
                if(!$editRes) return json(['err' => '5', 'msg' => '人员信息保存失败']);
                return json(['err' => '0', 'msg' => '人员信息已保存成功']);
            }catch (\think\Exception $e){ // use think\Exception;
               return json(['err' => '6', 'msg' => '失败：' . $e->getMessage()]);
            }
        }
        $info = ClinicAdmin::where(['is_del' => '0', 'id' => (int)$id, 'clinic_id' => $this->admin['clinic_id']])->find();
        $this->assign([
            'info' => $info,
            'page_title' => !$info ? '添加' : '修改',
            'group_list' => ClinicAuthGroup::getGroupList($this->admin['clinic_id'],true),
            'zhiwei_list' => ClinicDict::getAdminZhiWeiList(), //员工职位列表
            'zhicheng_list' => ClinicDict::getAdminZhiChengList(), //员工医师职称列表
            'zhengjian_list' => ClinicDict::getRenYuanZhengJianList(), //人员证件类型列表
            'xueli_list' => ClinicDict::getRenYuanXueLiList(), //人员学历类型列表
            'keshi_list' => ClinicDictsheet::getClinicKeShiList($this->admin['clinic_id'],true,'id,pid,name',['status' => '1']), //获取科室列表 Select 选择器使用
        ]);
        return $this->view->fetch();
    }
    //dialog 对话框添加
    public function dialog_add()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        $data = $this->request->only([
            'id','nickname','user_mobile','user_name','user_pwd','group_id','zhiwei_code','keshi_list','gonghao_code','sex','status',
            'captcha_code','captcha_key','phone_code',
        ],'post');
        if(!isset($data['id']))
        {
            return json(['err' => '2', 'msg' => '对不起，参数错误']); 
        }
        if(!isset($data['gonghao_code']) || $data['gonghao_code'] == '')
        {
            return json(['err' => '2', 'msg' => '请输入人员工号']); 
        }
        if(!isset($data['nickname']) || $data['nickname'] == '')
        {
            return json(['err' => '2', 'msg' => '请输入真实姓名']); 
        }
        if(!isset($data['user_mobile']) || $data['user_mobile'] == '')
        {
            return json(['err' => '2', 'msg' => '请输入手机号码']); 
        }
        if(!isset($data['user_pwd']) || $data['user_pwd'] == '')
        {
            return json(['err' => '2', 'msg' => '请输入手机号码']); 
        }
        if(strlen($data['user_pwd']) < 6)
        {
            return json(['err' => '2', 'msg' => '密码必须大于6位']); 
        }
        if(!isset($data['captcha_code']) || $data['captcha_code'] == '')
        {
            return json(['err' => '2', 'msg' => '请输入图形验证码']); 
        }
        if(!captcha_check($data['captcha'],$data['captcha_key'])){
            return json(['err' => '2', 'msg' => '图形验证码输入错误']);
        }
        try
        {
            $info = ClinicAdmin::where(['id' => intval($data['id']), 'clinic_id' => $this->admin['clinic_id']])->find();
            if($info)
            {
                return json(['err' => '3', 'msg' => '对不起，参数错误，操作受限']); 
            }
            unset($data['id']);
            //密码
            $pwdSalt = Random::numeric(5);
            $userPwd = ClinicAdmin::encryptPassword($data['user_pwd'],$pwdSalt);
            $data['user_pwd'] = $pwdSalt; //密码
            $data['pwd_salt'] = $pwdSalt; //密码域
            $isExists = ClinicAdmin::checkUniqueCode(new ClinicAdmin(),$data['user_name'],'user_name');
            if($isExists)
            {
                return json(['err' => '4', 'msg' => $data['user_name'] . '已被他人使用']);
            }
            $isExists = ClinicAdmin::checkUniqueCode(new ClinicAdmin(),$data['user_mobile'],'user_mobile');
            if($isExists)
            {
                return json(['err' => '5', 'msg' => $data['user_mobile'] . '已被他人使用']);
            }
            if(strlen($data['user_name']) <= 8)
            {
                return json(['err' => '6', 'msg' => '登录账号不可小于8位']);
            }
            //1.检查手机号对应的验证码是否正确
            $chName = md5($this->site['cookie_pre'] . 'sms_send_code_' . $data['user_mobile']);
            $yzmRes = Session::get($chName);
            if($yzmRes) $yzmRes = json_decode($yzmRes,true);
            if(!$yzmRes || !isset($yzmRes['num']) || (isset($yzmRes['exp']) && time() > $yzmRes['exp']))
            {
                return json(['err' => '7', 'msg' => '手机验证码已失效，请重新获取']);
            }
            if(empty($data['code']) || $data['code'] != $yzmRes['num'] || empty($yzmRes['num']))
            {
                return json(['err' => '8', 'msg' => '对不起，手机验证码不正确']);
            }
            Session::delete($chName);
            //2.写入数据
            $data['clinic_id'] = $this->admin['clinic_id']; //诊所门店表的id
            $data['create_time'] = time(); //创建时间
            $editRes = ClinicAdmin::insertGetId($data);
            if(!$editRes) return json(['err' => '6', 'msg' => '人员信息保存失败']);
            return json(['err' => '0', 'msg' => '人员信息已保存成功']);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '失败：' . $e->getMessage()]);
        }
    }
    //删除
    public function del()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        $data = $this->request->only(['id']);
        if(intval($data['id']) <= 0){
            return json(['err' => '2', 'msg' => '参数错误，请重试']);
        }
        //条件
        $map = [['id','in',$data['id']],['is_supper_admin','=','0'],['clinic_id','=',$this->admin['clinic_id']]];
        $r = ClinicAdmin::where($map)->update(['is_del' => '1']);
        if(!$r) return json(['err' => '3', 'msg' => '删除失败，请重试']);
        return json(['err' => '0', 'msg' => '删除成功']);
    }
    //修改登录密码
    public function edit_password()
    {
        if($this->request->isAjax())
        {
            $data = $this->request->only(['editmode','captcha_key','captcha','code','pwd','pwd1'],'post');
            if(!captcha_check($data['captcha'],$data['captcha_key'])){
                return json(['err' => '1', 'msg' => '对不起，图形验证码输入错误']);
            }
            if($data['pwd'] != $data['pwd1'])
            {
                return json(['err' => '2', 'msg' => '对不起，两次输入的密码不一致']);
            }
            if(strtolower($data['editmode']) == 'one') //使用手机验证码修改登录密码
            {
                //1.检查手机号对应的验证码是否正确
                $chName = md5($this->site['cookie_pre'] . 'sms_send_code_' . $this->admin['user_mobile']);
                $yzmRes = Session::get($chName);
                if($yzmRes) $yzmRes = json_decode($yzmRes,true);
                if(!$yzmRes || !isset($yzmRes['num']) || (isset($yzmRes['exp']) && time() > $yzmRes['exp']))
                {
                    return json(['err' => '3', 'msg' => '手机验证码已失效，请重新获取']);
                }
                if(empty($data['code']) || $data['code'] != $yzmRes['num'] || empty($yzmRes['num']))
                {
                    return json(['err' => '4', 'msg' => '对不起，手机验证码不正确']);
                }
                Session::delete($chName);
            }else{ //使用原登录密码 修改登录密码
                $oldPwd = ClinicAdmin::encryptPassword($data['code'],$this->admin['pwd_salt']);
                if($oldPwd != $this->admin['user_pwd'])
                {
                    return json(['err' => '3', 'msg' => '对不起，原密码验证失败']);
                }
            }
            $r = ClinicAdmin::resetPassword($this->admin['id'],$data['pwd1'],Random::numeric(5));
            if($r)
            {
                return json(['err' => '0', 'msg' => '密码修改成功，请妥善保管']);
            }else{
                return json(['err' => '5', 'msg' => '密码修改失败']);
            }
        }
        $this->assign(['captcha_key' => md5($this->site['client_uuid'] . '_2')]);
        if($this->admin['user_mobile']) //有手机号时
        {
            $this->assign(['edit_mode' => 'one']);
            return $this->view->fetch(); //使用手机验证码修改登录密码
        }else{
            $this->assign(['edit_mode' => 'two']);
            return $this->view->fetch('edit_password_two'); //使用原登录密码 修改登录密码 
        }
    }
    //修改手机号码
    public function edit_mobile()
    {
        if($this->request->isAjax())
        {
            $data = $this->request->only(['captcha_key','captcha','code','new_phone'],'post');
            if(!captcha_check($data['captcha'],$data['captcha_key'])){
                return json(['err' => '1', 'msg' => '对不起，图形验证码输入错误']);
            }
            if(!$data['new_phone'])
            {
                return json(['err' => '2', 'msg' => '对不起，手机号码不能为空']);
            }
            //1.检查手机号对应的验证码是否正确
            $chName = md5($this->site['cookie_pre'] . 'sms_send_code_' . $data['new_phone']);
            $yzmRes = Session::get($chName);
            if($yzmRes) $yzmRes = json_decode($yzmRes,true);
            if(!$yzmRes || !isset($yzmRes['num']) || (isset($yzmRes['exp']) && time() > $yzmRes['exp']))
            {
                return json(['err' => '3', 'msg' => '手机验证码已失效，请重新获取']);
            }
            if(empty($data['code']) || $data['code'] != $yzmRes['num'] || empty($yzmRes['num']))
            {
                return json(['err' => '4', 'msg' => '对不起，手机验证码不正确']);
            }
            Session::delete($chName);
            //2.修改手机号码
            $r = ClinicAdmin::where(['id' => $this->admin['id']])->update(['user_mobile' => $data['new_phone']]);
            if($r)
            {
                return json(['err' => '0', 'msg' => '手机号修改成功']);
            }else{
                return json(['err' => '5', 'msg' => '手机号修改失败']);
            }
        }
        $this->assign(['captcha_key' => md5($this->site['client_uuid'] . '_3')]);
        return $this->view->fetch();
    }
    //修改个人资料
    public function edit_myself()
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            $data = $this->request->only(['user_name','nickname','sex'],'post');
            try
            {
                $info = ClinicAdmin::where(['id' => intval($this->admin['id']), 'clinic_id' => $this->admin['clinic_id']])->find();
                if(!$info)
                {
                    return json(['err' => '1', 'msg' => '信息获取失败，禁止修改']);
                }
                $sqlData = [
                    'user_name' => $data['user_name'], //名称
                    'nickname' => $data['nickname'], //用户姓名
                    'sex' => (int)$data['sex'], //性别1.男2.女,0未知
                ];
                if(strlen($data['user_name']) <= 8)
                {
                    return json(['err' => '6', 'msg' => '登录账号不可小于8位']);
                }
                if($data['user_name'] != $info['user_name'])
                {
                    $isExists = ClinicAdmin::checkUniqueCode(new ClinicAdmin(),$data['user_name'],'user_name');
                    if($isExists)
                    {
                        return json(['err' => '2', 'msg' => $data['user_name'] . '已被他人使用']);
                    }
                }
                $editRes = ClinicAdmin::where(['id' => $info['id']])->update($sqlData);
                if(!$editRes) return json(['err' => '3', 'msg' => '个人资料信息保存失败']);
                return json(['err' => '0', 'msg' => '个人资料保存成功']);
            }catch (\think\Exception $e){ // use think\Exception;
               return json(['err' => '4', 'msg' => '失败：' . $e->getMessage()]);
            }
        }
        return $this->view->fetch();
    }
    //生成系统账号
    public function build_user_name()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        return json([
            'err' => '0',
            'msg' => '生成成功',
            'data' => ClinicAdmin::buildUniqueFieldsVal(5,'user_name'), //生成10位 数字+字母 登录账号
        ]);
    }
}
